<template>
  <view class="container">
    <view v-if="loading" class="loading-state">
      <uni-load-more status="loading" />
    </view>
    
    <view v-else-if="product" class="order-create">
      <!-- 商品信息 -->
      <view class="product-section">
        <view class="section-title">商品信息</view>
        <view class="product-item">
          <image 
            :src="product.image_url || '/static/icons/default-product.png'" 
            mode="aspectFill"
            class="product-image"
          />
          <view class="product-info">
            <view class="product-name">{{ product.name || '未知商品' }}</view>
          <view class="product-price">
            <text class="price-number">{{ product.points_price || 0 }}</text>
            <text class="price-unit">积分</text>
          </view>
          <view class="product-stock">
            库存: {{ product.stock_quantity || 0 }}
          </view>
          </view>
        </view>
      </view>

      <!-- 数量选择 -->
      <view class="quantity-section">
        <view class="section-title">选择数量</view>
        <view class="quantity-selector">
          <button 
            class="quantity-btn" 
            :disabled="quantity <= 1"
            @click="decreaseQuantity"
          >
            -
          </button>
          <input 
            v-model.number="quantity" 
            type="number" 
            class="quantity-input"
            :min="1"
            :max="product.stock_quantity || 999"
            @blur="validateQuantity"
          />
          <button 
            class="quantity-btn" 
            :disabled="quantity >= (product.stock_quantity || 999)"
            @click="increaseQuantity"
          >
            +
          </button>
        </view>
      </view>

      <!-- 打印选项（如果是打印类商品） -->
      <view v-if="isPrintProduct" class="print-options-section">
        <view class="section-title">打印选项</view>
        <view class="option-group">
          <view class="option-label">纸张大小</view>
          <picker 
            :value="printOptions.paperSize" 
            :range="paperSizes"
            range-key="label"
            @change="onPaperSizeChange"
          >
            <view class="picker-display">
              {{ getPaperSizeLabel(printOptions.paperSize) }}
            </view>
          </picker>
        </view>
        
        <view class="option-group">
          <view class="option-label">打印方向</view>
          <picker 
            :value="printOptions.orientation" 
            :range="orientations"
            range-key="label"
            @change="onOrientationChange"
          >
            <view class="picker-display">
              {{ getOrientationLabel(printOptions.orientation) }}
            </view>
          </picker>
        </view>
        
        <view class="option-group">
          <view class="option-label">双面打印</view>
          <switch 
            :checked="printOptions.duplex" 
            @change="onDuplexChange"
          />
        </view>
      </view>

      <!-- 订单类型 -->
      <view class="type-section">
        <view class="section-title">兑换方式</view>
        <view class="type-options">
          <view 
            class="type-option"
            :class="{ active: orderType === 'offline' }"
            @click="selectOrderType('offline')"
          >
            <view class="type-icon">🏪</view>
            <view class="type-text">
              <view class="type-name">到店兑换</view>
              <view class="type-desc">生成预约码，到店兑换</view>
            </view>
          </view>
          <view 
            class="type-option"
            :class="{ active: orderType === 'online' }"
            @click="selectOrderType('online')"
          >
            <view class="type-icon">📱</view>
            <view class="type-text">
              <view class="type-name">在线处理</view>
              <view class="type-desc">上传文件，在线处理</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 备注 -->
      <view class="notes-section">
        <view class="section-title">备注信息</view>
        <textarea 
          v-model="notes" 
          placeholder="请输入备注信息（选填）"
          class="notes-input"
          maxlength="200"
        />
      </view>

      <!-- 费用明细 -->
      <view class="cost-section">
        <view class="section-title">费用明细</view>
        <view class="cost-item">
          <text class="cost-label">商品单价</text>
          <text class="cost-value">{{ product.points_price || 0 }} 积分</text>
        </view>
        <view class="cost-item">
          <text class="cost-label">数量</text>
          <text class="cost-value">{{ quantity }}</text>
        </view>
        <view class="cost-item total">
          <text class="cost-label">总计</text>
          <text class="cost-value">{{ totalPoints }} 积分</text>
        </view>
      </view>

      <!-- 用户积分 -->
      <view class="user-points-section">
        <view class="points-info">
          <text class="points-label">我的积分:</text>
          <text class="points-value">{{ userPoints }}</text>
        </view>
        <view v-if="!hasEnoughPoints" class="insufficient-warning">
          积分不足，还需要 {{ totalPoints - userPoints }} 积分
        </view>
      </view>

      <!-- 底部操作 -->
      <view class="bottom-actions">
        <button 
          class="btn btn-primary"
          :disabled="!canCreateOrder || creating"
          @click="handleCreateOrder"
        >
          {{ creating ? '创建中...' : '确认兑换' }}
        </button>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else class="error-state">
      <image src="/static/icons/error.png" class="error-icon" />
      <text class="error-text">商品不存在或已下架</text>
      <button class="btn btn-secondary" @click="goBack">返回</button>
    </view>
  </view>
</template>

<script>
import { getProductDetail } from '@/api/products'
import { createOrder, validateOrder } from '@/api/orders'
import { mapGetters } from 'vuex'

export default {
  name: 'OrderCreatePage',
  data() {
    return {
      loading: true,
      creating: false,
      product: null,
      productId: null,
      quantity: 1,
      orderType: 'offline',
      notes: '',
      printOptions: {
        paperSize: 'A4',
        orientation: 'portrait',
        duplex: false
      },
      paperSizes: [
        { value: 'A4', label: 'A4' },
        { value: 'A3', label: 'A3' },
        { value: 'A5', label: 'A5' }
      ],
      orientations: [
        { value: 'portrait', label: '纵向' },
        { value: 'landscape', label: '横向' }
      ]
    }
  },
  
  computed: {
    ...mapGetters(['userInfo', 'userPoints']),
    
    isPrintProduct() {
      return this.product && this.product.category === 'print'
    },
    
    totalPoints() {
      if (!this.product) return 0
      const price = parseFloat(this.product.points_price) || 0
      return price * this.quantity
    },
    
    hasEnoughPoints() {
      return this.userPoints >= this.totalPoints
    },
    
    canCreateOrder() {
      return this.product && 
             this.quantity > 0 && 
             this.quantity <= (this.product.stock_quantity || 999) &&
             this.hasEnoughPoints
    },
  },
  
  onLoad(options) {
    if (options.productId) {
      this.productId = parseInt(options.productId)
      this.orderType = options.type || 'offline'
      this.loadProductDetail()
    } else {
      this.loading = false
    }
  },
  
  methods: {
    // 加载商品详情
    async loadProductDetail() {
      try {
        this.loading = true
        const response = await getProductDetail(this.productId)
        
        if (response.success && response.data) {
          this.product = response.data
          // 设置默认数量，但不超过库存
          this.quantity = Math.min(1, this.product.stock_quantity || 1)
        } else {
          this.product = null
        }
      } catch (error) {
        console.error('加载商品详情失败:', error)
        this.product = null
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 增加数量
    increaseQuantity() {
      if (this.quantity < (this.product.stock_quantity || 999)) {
        this.quantity++
      }
    },
    
    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--
      }
    },
    
    // 验证数量
    validateQuantity() {
      if (this.quantity < 1) {
        this.quantity = 1
      } else if (this.quantity > (this.product.stock_quantity || 999)) {
        this.quantity = this.product.stock_quantity || 999
        uni.showToast({
          title: '数量不能超过库存',
          icon: 'none'
        })
      }
    },
    
    // 选择订单类型
    selectOrderType(type) {
      this.orderType = type
    },
    
    // 纸张大小变化
    onPaperSizeChange(e) {
      this.printOptions.paperSize = this.paperSizes[e.detail.value].value
    },
    
    // 打印方向变化
    onOrientationChange(e) {
      this.printOptions.orientation = this.orientations[e.detail.value].value
    },
    
    // 双面打印变化
    onDuplexChange(e) {
      this.printOptions.duplex = e.detail.value
    },
    
    // 获取纸张大小标签
    getPaperSizeLabel(value) {
      const item = this.paperSizes.find(p => p.value === value)
      return item ? item.label : value
    },
    
    // 获取打印方向标签
    getOrientationLabel(value) {
      const item = this.orientations.find(o => o.value === value)
      return item ? item.label : value
    },
    
    // 创建订单
    async handleCreateOrder() {
      if (!this.canCreateOrder || this.creating) return
      
      try {
        this.creating = true
        
        // 构建订单数据
        const orderData = {
          type: this.orderType,
          items: [
            {
              productId: this.productId,
              quantity: this.quantity,
              printOptions: this.isPrintProduct ? this.printOptions : null
            }
          ],
          notes: this.notes.trim() || undefined
        }
        
        // 先验证订单
        const validation = await validateOrder(orderData)
        if (!validation.success || !validation.data.valid) {
          throw new Error((validation.data.items && validation.data.items[0] && validation.data.items[0].error) || '订单验证失败')
        }
        
        // 创建订单
        const response = await createOrder(orderData)
        
        if (response.success) {
          uni.showToast({
            title: '兑换成功',
            icon: 'success'
          })
          
          // 跳转到订单详情页
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/orders/detail?id=${response.data.id}`
            })
          }, 1500)
        } else {
          throw new Error(response.message || '创建订单失败')
        }
        
      } catch (error) {
        console.error('创建订单失败:', error)
        uni.showToast({
          title: error.message || '兑换失败',
          icon: 'none'
        })
      } finally {
        this.creating = false
      }
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.loading-state {
  padding: 100rpx 40rpx;
}

.order-create {
  padding: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.product-section,
.quantity-section,
.print-options-section,
.type-section,
.notes-section,
.cost-section,
.user-points-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.product-item {
  display: flex;
  align-items: center;
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.product-price {
  display: flex;
  align-items: baseline;
  margin-bottom: 8rpx;
}

.price-number {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff4757;
}

.price-unit {
  font-size: 24rpx;
  color: #ff4757;
  margin-left: 4rpx;
}

.product-stock {
  font-size: 24rpx;
  color: #666;
}

.quantity-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #f0f0f0;
  border: none;
  font-size: 32rpx;
  color: #333;
  
  &:disabled {
    background-color: #e0e0e0;
    color: #999;
  }
}

.quantity-input {
  width: 120rpx;
  height: 60rpx;
  text-align: center;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.option-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.option-label {
  font-size: 28rpx;
  color: #333;
}

.picker-display {
  padding: 12rpx 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #666;
}

.type-options {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.type-option {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  
  &.active {
    border-color: #007aff;
    background-color: #f0f8ff;
  }
}

.type-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.type-text {
  flex: 1;
}

.type-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 4rpx;
}

.type-desc {
  font-size: 24rpx;
  color: #666;
}

.notes-input {
  width: 100%;
  min-height: 120rpx;
  padding: 16rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 26rpx;
  resize: none;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &.total {
    padding-top: 12rpx;
    border-top: 1rpx solid #f0f0f0;
    font-weight: bold;
  }
}

.cost-label {
  font-size: 28rpx;
  color: #666;
}

.cost-value {
  font-size: 28rpx;
  color: #333;
}

.points-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.points-label {
  font-size: 28rpx;
  color: #666;
}

.points-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff4757;
}

.insufficient-warning {
  font-size: 24rpx;
  color: #ff4757;
  text-align: center;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 32rpx;
  border: none;
}

.btn-primary {
  background-color: #007aff;
  color: #fff;
  
  &:disabled {
    background-color: #ccc;
    color: #999;
  }
}

.btn-secondary {
  background-color: #f0f0f0;
  color: #666;
}

.error-state {
  text-align: center;
  padding: 100rpx 40rpx;
}

.error-icon {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}

.error-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}
</style>